package org.x.auth.controller;


import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaTokenInfo;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.x.api.system.dto.UserDTO;
import org.x.api.system.feign.RemoteLogService;
import org.x.api.system.feign.RemoteTenantService;
import org.x.api.system.feign.RemoteUserService;
import org.x.auth.dto.LoginRequest;
import org.x.api.system.dto.TenantDTO;
import org.x.auth.vo.TenantVO;
import org.x.common.base.constants.UserContext;
import org.x.common.base.result.Result;
import org.x.common.base.result.ResultCode;
import org.x.common.web.utils.RemoteLogKit;
import org.x.satoken.kit.StpKit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @DubboReference(version = "1.0.0", group = "x-user")
    private RemoteUserService remoteUserService;

    @DubboReference(version = "1.0.0", group = "x-log",async = true)
    private RemoteLogService remoteLogService;

    @DubboReference(version = "1.0.0", group = "x-tenant")
    private RemoteTenantService remoteTenantService;


    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        // 1. 验证用户凭证
        UserDTO user = remoteUserService.getUserByUsername(loginRequest.getUsername());

        if (user == null) {
            RemoteLogKit.sendLoginLog(remoteLogService,loginRequest.getUsername(), ResultCode.USER_NOT_FOUND);
            return Result.error(ResultCode.USER_NOT_FOUND);
        }

        String pw_hash = BCrypt.hashpw(loginRequest.getPassword(), BCrypt.gensalt());

        if( pw_hash.equals(user.getPassword())) {
            RemoteLogKit.sendLoginLog(remoteLogService,loginRequest.getUsername(), ResultCode.INVALID_PASSWORD);
            return Result.error(ResultCode.INVALID_PASSWORD);
        }
        //多套用户表登录体系的登录方式
        StpKit.getStpLogic().login(user.getUsername());
        StpKit.getStpLogic().getSession().set("USER", JSON.toJSONString(user));
        StpKit.getStpLogic().getSession().set(UserContext.TENANT_ID, request.getHeader(UserContext.TENANT_ID));

        // 3. 记录成功日志
     //   RemoteLogKit.sendLoginLog(remoteLogService,loginRequest.getUsername(), ResultCode.LOGIN_SUCCESS);

        // 登录成功后返回用户ID和token信息
        SaTokenInfo tokenInfo = StpKit.getStpLogic().getTokenInfo();

        // 手动构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("tokenName", tokenInfo.getTokenName());
        result.put("tokenValue", tokenInfo.getTokenValue());
        result.put("loginDevice", tokenInfo.getLoginDevice());
        result.put("loginId", tokenInfo.getLoginId());
        result.put("userId", user.getId()); // 添加用户ID

        return Result.success(result);
    }

    @GetMapping("/logout")
    public Result<?> logout() {
        StpKit.getStpLogic().logout();
        return Result.success();
    }

    // 新增租户列表接口
    @GetMapping("/tenants")
    public Result<?> getTenants() {
        try {
            List<TenantDTO> tenants = remoteTenantService.getActiveTenants();
            List<TenantVO> voList = tenants.stream()
                    .map(t -> new TenantVO(t.getId(), t.getName(),t.getCode(),t.getStatus()))
                    .collect(Collectors.toList());
            return Result.success(voList);
        } catch (Exception e) {
            return Result.error(ResultCode.SERVICE_UNAVAILABLE);
        }
    }
}